#!/bin/bash
# Arch Linux 系统配置脚本
# 在 arch-chroot 环境中运行
# 用途：快速完成系统基础配置和 bootloader 安装

set -e

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印函数
print_step() {
    echo -e "${BLUE}===================================${NC}"
    echo -e "${BLUE}  $1${NC}"
    echo -e "${BLUE}===================================${NC}"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

# 检查是否在 chroot 环境中
if [ ! -f /etc/arch-release ]; then
    print_error "此脚本必须在 arch-chroot 环境中运行！"
    exit 1
fi

echo ""
echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}    Arch Linux 系统配置向导${NC}"
echo -e "${GREEN}=========================================${NC}"
echo ""
echo "此脚本将配置："
echo "  1. 时区和时间"
echo "  2. 系统语言"
echo "  3. 主机名"
echo "  4. Root 密码"
echo "  5. 创建用户"
echo "  6. 网络服务"
echo "  7. Bootloader"
echo ""
read -p "按 Enter 继续，Ctrl+C 取消..."

# ============================================
# 第 1 步：配置时区
# ============================================
print_step "第 1 步：配置时区"

echo "常用时区："
echo "  1. Asia/Shanghai (中国)"
echo "  2. Asia/Hong_Kong (香港)"
echo "  3. Asia/Tokyo (日本)"
echo "  4. America/New_York (美国东部)"
echo "  5. Europe/London (英国)"
echo "  6. 自定义"
echo ""
read -p "选择时区 [1-6，默认 1]: " timezone_choice

case ${timezone_choice:-1} in
    1) TIMEZONE="Asia/Shanghai" ;;
    2) TIMEZONE="Asia/Hong_Kong" ;;
    3) TIMEZONE="Asia/Tokyo" ;;
    4) TIMEZONE="America/New_York" ;;
    5) TIMEZONE="Europe/London" ;;
    6)
        read -p "输入时区（如 Asia/Shanghai）: " TIMEZONE
        ;;
    *) TIMEZONE="Asia/Shanghai" ;;
esac

ln -sf /usr/share/zoneinfo/$TIMEZONE /etc/localtime
hwclock --systohc
print_success "时区设置为: $TIMEZONE"

# ============================================
# 第 2 步：配置语言
# ============================================
print_step "第 2 步：配置系统语言"

echo "启用语言："
echo "  1. 英文 + 中文 (推荐)"
echo "  2. 仅英文"
echo "  3. 仅中文"
echo ""
read -p "选择 [1-3，默认 1]: " lang_choice

case ${lang_choice:-1} in
    1)
        sed -i 's/#en_US.UTF-8/en_US.UTF-8/' /etc/locale.gen
        sed -i 's/#zh_CN.UTF-8/zh_CN.UTF-8/' /etc/locale.gen
        LANG="en_US.UTF-8"
        print_success "启用: 英文 + 中文"
        ;;
    2)
        sed -i 's/#en_US.UTF-8/en_US.UTF-8/' /etc/locale.gen
        LANG="en_US.UTF-8"
        print_success "启用: 仅英文"
        ;;
    3)
        sed -i 's/#zh_CN.UTF-8/zh_CN.UTF-8/' /etc/locale.gen
        LANG="zh_CN.UTF-8"
        print_success "启用: 仅中文"
        ;;
    *)
        sed -i 's/#en_US.UTF-8/en_US.UTF-8/' /etc/locale.gen
        sed -i 's/#zh_CN.UTF-8/zh_CN.UTF-8/' /etc/locale.gen
        LANG="en_US.UTF-8"
        print_success "启用: 英文 + 中文"
        ;;
esac

locale-gen
echo "LANG=$LANG" > /etc/locale.conf
print_success "系统语言设置完成"

# ============================================
# 第 3 步：配置主机名
# ============================================
print_step "第 3 步：配置主机名"

read -p "输入主机名 [默认: archlinux]: " hostname
hostname=${hostname:-archlinux}
echo "$hostname" > /etc/hostname
print_success "主机名设置为: $hostname"

# ============================================
# 第 4 步：设置 Root 密码
# ============================================
print_step "第 4 步：设置 Root 密码"

echo "请设置 root 密码："
while ! passwd; do
    print_warning "密码设置失败，请重试"
done
print_success "Root 密码设置完成"

# ============================================
# 第 5 步：创建用户
# ============================================
print_step "第 5 步：创建普通用户"

read -p "输入用户名 [默认: user]: " username
username=${username:-user}

if id "$username" &>/dev/null; then
    print_warning "用户 $username 已存在，跳过创建"
else
    useradd -m -G wheel "$username"
    print_success "用户 $username 创建成功"
fi

echo "请设置用户 $username 的密码："
while ! passwd "$username"; do
    print_warning "密码设置失败，请重试"
done
print_success "用户密码设置完成"

# 启用 sudo
sed -i 's/# %wheel ALL=(ALL:ALL) ALL/%wheel ALL=(ALL:ALL) ALL/' /etc/sudoers
print_success "Sudo 权限已启用"

# ============================================
# 第 6 步：配置网络
# ============================================
print_step "第 6 步：配置网络"

systemctl enable NetworkManager
print_success "NetworkManager 已启用"

# ============================================
# 第 7 步：安装 Bootloader
# ============================================
print_step "第 7 步：安装 Bootloader"

echo ""
echo "选择 Bootloader："
echo ""
echo "  1. systemd-boot (推荐真实硬件)"
echo "     - 优点: 简单、快速、UEFI 原生"
echo "     - 缺点: 仅支持 UEFI"
echo "     - 注意: VirtualBox 可能需要额外配置"
echo ""
echo "  2. GRUB (推荐 VirtualBox)"
echo "     - 优点: 功能强大、兼容性好"
echo "     - 缺点: 配置稍复杂"
echo "     - 推荐: VirtualBox 虚拟机"
echo ""
read -p "选择 [1 或 2]: " bootloader_choice

case $bootloader_choice in
    1)
        print_step "安装 systemd-boot"
        
        bootctl install
        
        # 修复权限
        if [ -d /boot/efi ]; then
            chmod 700 /boot/efi
            chmod 600 /boot/efi/loader/random-seed 2>/dev/null || true
            print_success "EFI 分区权限已修复"
        fi
        
        # 获取 PARTUUID
        ROOT_PARTUUID=$(blkid -s PARTUUID -o value /dev/sda2)
        
        if [ -z "$ROOT_PARTUUID" ]; then
            print_error "无法获取根分区 PARTUUID"
            exit 1
        fi
        
        # 创建 loader.conf
        cat > /boot/efi/loader/loader.conf << EOF
default arch.conf
timeout 3
console-mode max
editor no
EOF
        print_success "loader.conf 创建完成"
        
        # 创建 arch.conf
        cat > /boot/efi/loader/entries/arch.conf << EOF
title   Arch Linux
linux   /vmlinuz-linux
initrd  /initramfs-linux.img
options root=PARTUUID=$ROOT_PARTUUID rw rootflags=subvol=@ quiet
EOF
        print_success "启动条目创建完成"
        
        # 验证
        echo ""
        echo "=== 验证配置 ==="
        echo "--- loader.conf ---"
        cat /boot/efi/loader/loader.conf
        echo ""
        echo "--- arch.conf ---"
        cat /boot/efi/loader/entries/arch.conf
        echo ""
        
        # 检查关键文件
        if [ -f /boot/efi/EFI/BOOT/BOOTX64.EFI ]; then
            print_success "BOOTX64.EFI 已创建"
        else
            print_warning "BOOTX64.EFI 未找到"
        fi
        
        print_success "systemd-boot 安装完成"
        ;;
        
    2)
        print_step "安装 GRUB"
        
        # 检查是否已安装
        if ! command -v grub-install &> /dev/null; then
            echo "安装 GRUB 软件包..."
            pacman -S --noconfirm grub efibootmgr
        fi
        
        # 安装 GRUB
        grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=GRUB
        print_success "GRUB 引导程序已安装"
        
        # 生成配置
        grub-mkconfig -o /boot/grub/grub.cfg
        print_success "GRUB 配置文件已生成"
        
        # 验证
        echo ""
        echo "=== 验证安装 ==="
        if [ -f /boot/efi/EFI/GRUB/grubx64.efi ]; then
            print_success "grubx64.efi 已创建"
            ls -lh /boot/efi/EFI/GRUB/grubx64.efi
        else
            print_error "grubx64.efi 未找到"
        fi
        
        if [ -f /boot/grub/grub.cfg ]; then
            print_success "grub.cfg 已创建"
            echo "配置文件行数: $(wc -l < /boot/grub/grub.cfg)"
        else
            print_error "grub.cfg 未找到"
        fi
        
        print_success "GRUB 安装完成"
        ;;
        
    *)
        print_error "无效选择，Bootloader 安装跳过"
        print_warning "请手动安装 Bootloader！"
        ;;
esac

# ============================================
# 配置完成总结
# ============================================
echo ""
echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}    配置完成！${NC}"
echo -e "${GREEN}=========================================${NC}"
echo ""
echo "配置摘要："
echo "  时区:     $TIMEZONE"
echo "  语言:     $LANG"
echo "  主机名:   $hostname"
echo "  用户名:   $username"
echo "  网络:     NetworkManager"
if [ "$bootloader_choice" = "1" ]; then
    echo "  引导器:   systemd-boot"
elif [ "$bootloader_choice" = "2" ]; then
    echo "  引导器:   GRUB"
else
    echo "  引导器:   未安装"
fi
echo ""
echo "下一步："
echo "  1. 输入 'exit' 退出 chroot"
echo "  2. 运行 'umount -R /mnt' 卸载分区"
echo "  3. 运行 'reboot' 重启系统"
echo ""
if [ "$bootloader_choice" = "1" ]; then
    print_warning "提示：如果使用 VirtualBox 且 systemd-boot 无法启动"
    print_warning "      可以重新挂载系统，选择安装 GRUB"
fi
echo ""
print_success "祝你使用愉快！"
echo ""

